import Router from "koa-router"
import fs from "fs"
import path from "path"
import upload, {
  UPLOAD_DIR,
  chunkUploadStatus,
  chunkUpload
} from "@/utils/upload"

const UploadRouter = new Router()
UploadRouter.post("/file/upload", upload.array("file"), function (ctx) {
  // @ts-ignore
  const { files } = ctx.req
  if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR)
  console.log(files, "files")
  ctx.body = {
    message: "success",
    files: files.map((item) => ({
      mimetype: item.mimetype,
      filename: item.filename,
      size: item.size
    }))
  }
})
UploadRouter.post(
  "/file/chunkUpload",
  upload.single("file"),
  async function (ctx):Promise<any> {
    let code = 0
    try {
      // @ts-ignore
      const chunkIndex = Number(ctx.req.body.chunkIndex)
      // @ts-ignore
      const chunkSize = Number(ctx.req.body.chunkSize)
      // @ts-ignore
      const chunkTotal = Number(ctx.req.body.chunkTotal)
      // @ts-ignore
      const file = ctx.req.file
      // @ts-ignore
      const filename = ctx.req.body.filename
      const chunkPath = path.join(UPLOAD_DIR, filename + ".part" + chunkIndex)
      try {
        if (!filename) {
          const msg = "bad body params"
          console.error(msg)
          return ctx.throw(500, msg)
        }
        const fileBuffer = fs.readFileSync(file.path)
        if (!file) {
          const msg = "bad body file"
          // @ts-ignore
          console.error(msg)
           (ctx.body = { code, msg })
          return
        }

        await chunkUpload(fileBuffer, chunkPath) // 等待切片上传
        await chunkUploadStatus(filename, chunkIndex, chunkTotal) // 等待上传结果
        return (ctx.body = { message: "success", chunkIndex, code: 1 })
      } catch (e) {
        const errorFilePath = file.path
        console.log("router", errorFilePath)
        fs.existsSync(errorFilePath) &&
          fs.unlink(errorFilePath, function () {
            console.log("异步删除" + errorFilePath)
            console.log(chunkPath, "chunkPath")
            fs.unlinkSync(chunkPath)
          })
        if(e instanceof Error){
          // @ts-ignore
          console.error(e.message)
           (ctx.body = { code, msg: e.message })
          return
        }

      }
    } catch (e) {
     e instanceof Error && console.error(e.message)
    }
  }
)

export default UploadRouter
